#include	"../Headers/types.h"			
#include	"../Headers/config.h"		
#include	"../Headers/log.h"		
#include  "../Headers/authr.h"
#include  "../Headers/nsr.h"
#include  "../AR/authorization.h"
#include  "fs.rpc.h"
#include  "fs.file.h"
#include  "fs.server.h"
#include  <string>
#include  <iostream>

#ifndef CONFIG
#define CONFIG ("fs-server.cfg")
#endif 

using namespace TOB;

FS_Server::FS_Server() { 
	Config cfg(CONFIG);
	FS_Server::path = cfg.stringValue("path");
	std::ifstream in(FS_Server::path + "fileId");
	in >> FS_Server::fileId;
	in.close();
	//FS_Server::path = "Files/";
	//Log::event("Path.. " + FS_Server::path);
}

FS_Server::~FS_Server() {
	std::ofstream out(FS_Server::path + "fileId");
	out << FS_Server::fileId;
	out.close();
}

uint32 FS_Server::push(std::string fileName) {
	FS_Server::fileId++;	
	Log::event("Add file " + fileName);
	f.write(FS_Server::path + "0", toString(FS_Server::fileId) + " " + fileName + "\n");
	refresh();
	return FS_Server::fileId;
}

std::string FS_Server::pop(uint32 fileId) {
	std::string fileid = toString(fileId);
	std::string fileName = f.search(FS_Server::path + "0", fileid);
	if (fileName == "") { return "";}
	uint32 i;
	for (i = 0; i < fileName.length() && fileName[i] != ' '; i++);
	return fileName.replace(fileName.begin(), fileName.begin() + i + 1, "");
}

void FS_Server::refresh() {
	std::ofstream out(FS_Server::path + "fileId");
	out << FS_Server::fileId;
	out.close();
}

std::string FS_Server::toString(uint32 i) {
	std::stringstream ss;
	std::string result;
	ss << i;
	ss >> result;
	return result;
}

uint32 FS_Server::auth(Nameserver::IP nsip, std::string username, std::string password, bool* res) {
	Authorization ar(nsip, username, password);
	Code::Type code;
	if ((code = ar.FileSharing(*res)) != Code::Okay) { return code; }
	return Code::Okay;
}
